package com.bawei.module_home.vm

import com.bawei.lib_common.vm.BaseViewModel
import com.bawei.module_home.entriy.CommendEntity
import com.bawei.module_home.intent.HomeViewIntent
import com.bawei.module_home.repo.HomeRepository
import com.bawei.module_home.state.HomeUiState
import com.blankj.utilcode.util.GsonUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject

/**
 * 首页viewmodel
 *
 * StateFlow和iSharedFlow流的区别
 * 1.是否需要设置默认值：StateFlow必须设置，SharedFlow不需要
 * 2.是否接收相同的值：StateFlow不能，SharedFlow可以接收相同的状态
 * 3.是否存在缓存：StateFlow没有缓存，SharedFlow有缓存
 * 4.是否可以多次订阅接收数据：StateFlow不可以，SharedFlow可以
 */
@HiltViewModel
class HomeViewmodel @Inject constructor(private val apiserver:HomeRepository):BaseViewModel<HomeViewIntent>(){

    /**
     * 防止外部更改
     */
    //私有的防止外部修改StateFlow
    private val _uiStateFlow= MutableSharedFlow<HomeUiState>()
    //对外暴露一个StateFlow用于收集数据变化
    val uiStateFlow:SharedFlow<HomeUiState> = _uiStateFlow.asSharedFlow()


    /**
     * 分发View层的意图
     */
    override fun dispatchIntent(intent: HomeViewIntent) {
        when(intent){
            is HomeViewIntent.LoadVideType -> loadSimpleType()
            is HomeViewIntent.LoadRecommendSimpleVideoList -> loadRecommendSimpleVideoList(intent.pageIndex, intent.pageSize)
            is HomeViewIntent.LoadSimpleVideoList -> loadSimpleVideoListByChannelId(intent.channelId, intent.pageIndex, intent.pageSize)
            is HomeViewIntent.LoadVideoCommentList -> loadVideoCommentList(intent.dataType, intent.itemId)
            is HomeViewIntent.PublishVideoComment -> publishVideoComment(intent.entity)

        }
    }

    /**
     * 加载视频分类
     */
    private fun  loadSimpleType(){
        mViewModelScope.launch  (mDispatcher){
            //发送请求并手机数据
            apiserver.getSimpleType().collect{list->
                if(list.isNotEmpty()){
                  _uiStateFlow.emit(HomeUiState.LoadSimpleTypeSuccess(list))
                }else{
                    _uiStateFlow.emit(HomeUiState.LoadSimpleTypeFailed("没有请求成功分类数据"))
                }
            }
        }
    }

    /**
     * 获取推荐视频列表
     */
    private fun loadRecommendSimpleVideoList(page: Int, pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            //发送请求并收集数据
            apiserver.getRecommendSimpleVideoList(page, pageSize).collect{ list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(HomeUiState.LoadSimpleVideoSuccess(list))
                } else {
                    _uiStateFlow.emit(HomeUiState.LoadSimpleVideoFail("没有获取到该分类下的视频!"))
                }
            }
        }
    }

    /**
     * 获取分类下视频列表
     */
    private fun loadSimpleVideoListByChannelId(channelId: String, pageIndex: Int, pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            //发送请求并收集数据
            apiserver.getSimpleVideoList(channelId, pageIndex, pageSize).collect{ list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(HomeUiState.LoadSimpleVideoSuccess(list))
                } else {
                    _uiStateFlow.emit(HomeUiState.LoadSimpleVideoFail("没有获取到该分类下的视频!"))
                }
            }
        }

    }

    /**
     * 获取视频评论列表
     */
    private fun loadVideoCommentList(dataType: Int, itemId: String){
        mViewModelScope.launch(mDispatcher) {
            //发送请求并收集数据
            apiserver.getVideoCommends(itemId, dataType).collect{ list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(HomeUiState.LoadVideoCommentSuccess(list))
                } else {
                    _uiStateFlow.emit(HomeUiState.LoadVideoCommentFail("获取该视频评论列表失败!"))
                }
            }
        }

    }

    /**
     * 发布视频评论
     */
    private fun publishVideoComment(commentEntity: CommendEntity){
        mViewModelScope.launch(mDispatcher) {
            //发送请求并收集数据
            val requestBody: RequestBody = GsonUtils.toJson(commentEntity).toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
            apiserver.publishVideoComment(requestBody).collect{ list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(HomeUiState.PublishVideoCommentSuccess(list))
                } else {
                    _uiStateFlow.emit( HomeUiState.PublishVideoCommentFail("发布视频评论失败！"))
                }
            }
        }

    }
}